<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useUserStore } from "@/stores/user";
import { useUserAPI } from "@/services/user";
import UploadSongDialog from "@/components/dialog/UploadSongDialog.vue";
import { IconMusic, IconPlay, IconHeart } from "@/components/icons";
import { ElMessageBox, ElMessage } from "element-plus";

const userStore = useUserStore();
const userAPI = useUserAPI();
const songs = ref<any[]>([]);
const showUploadDialog = ref(false);
const sortBy = ref("latest"); // latest, popular
const searchQuery = ref("");

// 统计数据
const statistics = ref({
  totalSongs: 0,
  totalPlays: 0,
  totalFavorites: 0,
});

// 获取歌手的所有歌曲
const fetchArtistSongs = async () => {
  try {
    const res = await userAPI.getMusicianSongs(userStore.username);
    console.log(res.data);

    // 为每首歌添加模拟的播放次数和收藏次数
    songs.value = res.data.map((song:any) => ({
      ...song,
      playCount: 8 + Math.floor(Math.random() * 5), // 生成8-12之间的随机数
      favorCount: 3 + Math.floor(Math.random() * 4), // 生成3-6之间的随机数
    }));

    // 更新统计数据
    statistics.value.totalSongs = songs.value.length;
    statistics.value.totalPlays = songs.value.reduce(
      (sum, song) => sum + song.playCount,
      0
    );
    statistics.value.totalFavorites = songs.value.reduce(
      (sum, song) => sum + song.favorCount,
      0
    );
  } catch (error) {
    console.error("获取歌曲列表失败:", error);
  }
};

// 上传歌曲
const handleUpload = () => {
  showUploadDialog.value = true;
};

// 下架歌曲
const handleRemoveSong = async (song: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要下架歌曲 "${song.musicName}" 吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await userAPI.deleteSong(song.musicId);
    ElMessage.success("下架成功");
    await fetchArtistSongs();
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("下架歌曲失败:", error);
      ElMessage.error("下架失败，请重试");
    }
  }
};

// 格式化日期显示
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  }).format(date);
};

// 排序和筛选
const filteredSongs = computed(() => {
  let result = [...songs.value];

  // 搜索过滤
  if (searchQuery.value) {
    result = result.filter((song) =>
      song.musicName.toLowerCase().includes(searchQuery.value.toLowerCase())
    );
  }

  // 排序
  if (sortBy.value === "popular") {
    result.sort((a, b) => b.playCount - a.playCount);
  } else {
    result.sort(
      (a, b) =>
        new Date(b.musicPushDate || b.musicPublisDate).getTime() -
        new Date(a.musicPushDate || a.musicPublisDate).getTime()
    );
  }

  return result;
});

onMounted(() => {
  fetchArtistSongs();
});
</script>

<template>
  <div class="max-w-7xl mx-auto px-4 py-8">
    <!-- 头部统计区域 -->
    <div class="mb-8 grid grid-cols-1 md:grid-cols-3 gap-6">
      <div class="bg-white rounded p-4 border border-gray-200">
        <div class="text-3xl font-bold text-gray-900">
          {{ statistics.totalSongs }}
        </div>
        <div class="mt-2 text-sm text-gray-600">发布的作品</div>
      </div>
      <div class="bg-white rounded p-4 border border-gray-200">
        <div class="text-3xl font-bold text-gray-900">
          {{ statistics.totalPlays }}
        </div>
        <div class="mt-2 text-sm text-gray-600">总播放次数</div>
      </div>
      <div class="bg-white rounded p-4 border border-gray-200">
        <div class="text-3xl font-bold text-gray-900">
          {{ statistics.totalFavorites }}
        </div>
        <div class="mt-2 text-sm text-gray-600">总收藏次数</div>
      </div>
    </div>

    <!-- 操作栏 -->
    <div
      class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6"
    >
      <div class="flex items-center space-x-4 flex-1">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索我的作品..."
          class="px-4 py-2 w-full md:w-64 rounded border border-gray-300 focus:shadow-lg ring-1 ring-gray-200 outline-none"
        />
      </div>
      <button
        @click="handleUpload"
        class="px-6 py-2 bg-[#d51007] text-white rounded hover:bg-[#b31007] transition-colors"
      >
        上传新歌
      </button>
    </div>

    <!-- 歌曲列表 -->
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th
              class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
            >
              歌曲
            </th>
            <th
              class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
            >
              发布时间
            </th>
            <th
              class="px-6 py-4 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"
            >
              播放
            </th>
            <th
              class="px-6 py-4 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"
            >
              收藏
            </th>
            <th
              class="px-6 py-4 text-center text-xs font-medium text-gray-500 uppercase tracking-wider"
            >
              操作
            </th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
          <tr
            v-for="song in filteredSongs"
            :key="song.musicId"
            class="hover:bg-gray-50 transition-colors"
          >
            <td class="px-6 py-4 whitespace-nowrap">
              <div class="flex items-center gap-4">
                <img
                  :src="song.musicCoverUrl"
                  :alt="song.musicName"
                  class="w-12 h-12 object-cover rounded-md shadow-sm"
                />
                <div class="overflow-hidden">
                  <div class="font-medium text-gray-900 truncate max-w-[200px]">
                    {{ song.musicName }}
                  </div>
                  <div class="text-sm text-gray-500 truncate max-w-[200px]">
                    {{ song.musicAuthor }}
                  </div>
                </div>
              </div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <span class="text-sm text-gray-500">
                {{ formatDate(song.musicPushDate || song.musicPublisDate) }}
              </span>
            </td>
            <td class="px-6 py-4 text-right whitespace-nowrap">
              <span class="text-sm text-gray-500">{{
                song.playCount || 0
              }}</span>
            </td>
            <td class="px-6 py-4 text-right whitespace-nowrap">
              <span class="text-sm text-gray-500">{{
                song.favorCount || 0
              }}</span>
            </td>
            <td class="px-6 py-4 text-center whitespace-nowrap">
              <button
                @click="handleRemoveSong(song)"
                class="inline-flex items-center px-3 py-1 rounded-md text-sm text-[#d51007] hover:bg-red-50 transition-colors"
              >
                下架
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <UploadSongDialog
      v-model:show="showUploadDialog"
      @uploaded="fetchArtistSongs"
    />
  </div>
</template>

<style scoped>
.grid {
  grid-auto-rows: minmax(100px, auto);
}

/* 添加表格相关样式 */
.min-w-full {
  min-width: 100%;
}

/* 确保长文本不会破坏布局 */
.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
